const puppeteer = require('puppeteer')
const fs = require('fs')
let data = []
// 所有手机品牌
// https://cashify.cashify.in/brands?sgs=0&_v=0&plid=20
// dt.map(item=>item.bi)

// 获取该品牌的手机型号
// https://cashify.cashify.in/brand/products?os=0&ps=10&b_id=21

// 该型号产品的所有资料
// https://cashify.cashify.in/product/product-list?os=0&ps=10&s_id=1535
// https://cashify.cashify.in/product?id=11393
// https://cashify.cashify.in/calculator?eh=1&icd=0&ng=1&lr=2&pn=Apple%20Iphone%20SE%2064GB&pid=11393&bn=Apple%20iPhone&bid=21&plid=20&_v=0

/**
 * 获取Model
 */
async function getModel(page, index) {
  return new Promise(async (resolve, reject) => {
    try {
      const brand = await page.$(
        `#mob-nav > app-root > div > app-home > app-category-banner > section > div > div.banner-search.homewidget > div > div > app-site-brand-list > div.category-wrap > div > div > div.cat-item:nth-child(${index})`
      )
      brand.click()
      console.log('click')
      await page.waitForSelector(
        '#mob-nav > app-root > div > app-home > app-category-banner > section > div > div.banner-search.homewidget > div > div > app-site-brand-products'
      )
      setTimeout(async () => {
        let models = await page.evaluate(() => {
          const result = []
          const $models = document.querySelectorAll(
            '#mob-nav > app-root > div > app-home > app-category-banner > section > div > div.banner-search.homewidget > div > div > app-site-brand-products > div.category-wrap > div > div > div'
          )
          $models.forEach(elem => {
            result.push({ name: elem.innerText.trim() })
          })
          return result
        })

        for (let i = 0; i < models.length; i++) {
          const model = models[i]
          model.products = await getProduct(page, i + 1)
        }
        await page.evaluate(() => {
          history.back()
        })
        await page.waitForSelector(
          '#mob-nav > app-root > div > app-home > app-category-banner > section > div > div.banner-search.homewidget > div > div > app-site-brand-list'
        )
        setTimeout(() => {
          resolve(models)
        }, 1000)
      }, 2000)
    } catch (error) {
      console.log('error', error.message)
      reject(error)
    }
  })
}

/**
 * 获取产品分类
 */
async function getProduct(page, index) {
  return new Promise(async (resolve, reject) => {
    try {
      const brand = await page.$(
        `#mob-nav > app-root > div > app-home > app-category-banner > section > div > div.banner-search.homewidget > div > div > app-site-brand-products > div.category-wrap > div > div > div:nth-child(${index})`
      )
      console.log('model click')
      brand.click()
      await page.waitForSelector(
        '#mob-nav > app-root > div > app-home > app-category-banner > section > div > div.banner-search.homewidget > div > div > app-site-brand-products'
      )
      setTimeout(async () => {
        let products = await page.evaluate(() => {
          const result = []
          const $products = document.querySelectorAll(
            '#mob-nav > app-root > div > app-home > app-category-banner > section > div > div.banner-search.homewidget > div > div > app-site-brand-products > div.category-wrap > div > div > div'
          )
          $products.forEach(elem => {
            result.push(elem.innerText.trim())
          })
          return result
        })
        await page.evaluate(() => {
          history.back()
        })
        await page.waitForSelector(
          '#mob-nav > app-root > div > app-home > app-category-banner > section > div > div.banner-search.homewidget > div > div >app-site-brand-products'
        )
        setTimeout(() => {
          resolve(products)
        }, 1000)
      }, 2000)
    } catch (error) {
      console.log('error', error.message)
      reject(error)
    }
  })
}

async function run() {
  try {
    const browser = await puppeteer.launch({ headless: false })
    const page = await browser.newPage()
    await page.goto('https://www.cashify.in/inline-categories/sell-used-Mobile%20Phone-20?pn=Mobile%20Phone&pd=20')
    console.log('载入成功')

    const brands = await page.evaluate(() => {
      const $brands = document.querySelectorAll(
        '#mob-nav > app-root > div > app-home > app-category-banner > section > div > div.banner-search.homewidget > div > div > app-site-brand-list > div.category-wrap > div > div > div.cat-item'
      )
      // console.log($brands.length)
      const result = []
      $brands.forEach(elem => {
        result.push({ name: elem.innerText.trim() })
      })
      return result
    })
    console.log('获取所有品牌')
    // console.log(brands)
    data = brands
    for (let i = 0; i < brands.length; i++) {
      const brand = brands[i]
      const models = await getModel(page, i + 1)
      brand.models = models
      // console.log(brand.brand, models)
    }
    console.log(data)
    fs.writeFileSync('cashify_data.json', JSON.stringify(data))
    // browser.close()
  } catch (error) {
    console.log('global error', error)
  }
}

run()
